package com.wushi.lenovo.asia5b.app_ui.other.dialog;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.mvp.base.BaseDialog;
import com.mvp.dagger.modules.NetworkModule;
import com.mvp.utils.DisplayUtils;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_model.other.AdvModel;
import com.wushi.lenovo.asia5b.app_ui.h5.CategoryActivity;
import com.wushi.lenovo.asia5b.app_utils.helper.CrashHelper;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;

/**
 * 首页中弹出的消息dialog
 * 这个dialog暂时不用ConstraintLayout优化了
 */
public class AdvDialog extends BaseDialog implements View.OnClickListener {
    private final AdvModel model;
    @BindView(R.id.iv_mainmsg_img)
    ImageView iv_mainmsg_img;
    @BindView(R.id.iv_mainmsg_delete)
    ImageView iv_mainmsg_delete;
    @BindView(R.id.fl_mainmsg)
    FrameLayout fl_mainmsg;
    private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener;
    private final Bitmap resource;

    public static void showAdvDialog(Context context) {
        getAdvData(context);
    }

    private static void getAdvData(Context context) {
        ApiService apiService = NetworkModule.getRetrofit().create(ApiService.class);
        apiService.getAdvData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resultModel -> {
                    if (resultModel.isSuccess()) {
                        AdvModel advModel = resultModel.getData();
//                        if (GlobalValue.isDebug) {
//                            advModel = new AdvModel(
//                                    "https://res.cloudinary.com/dyyuqu2ka/image/upload/v1565779031/Popup%20Message/ulq2iq3d8qmzabwncyos.jpg",
//                                    0,
//                                    "https://www.facebook.com/notes/asia5b-online-shopping-b2b2c/asia5b-疯狂免抛呜啦啦-/2198336577124879/",
//                                    "socialmedia",
//                                    "facebook"
//                            );
//                        }
                        if (advModel != null && !TextUtils.isEmpty(advModel.getImage_url())) {
                            AdvDialog.showAdvDialog(context, advModel);
                        }
                    }
                }, throwable -> {
                    CrashHelper.postCatchedException(throwable);
                });
    }

    private static void showAdvDialog(Context context, AdvModel advModel) {
        final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_load_default);
        if (advModel != null) {
            String image_url = advModel.getImage_url();
//            if (GlobalValue.isDebug ) {
//                image_url = "https://res.cloudinary.com/dqfyvwfdj/image/upload/v1551686176/popup%20message/um0v27emthehywbuzjxu.jpg";
//                image_url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556433359759&di=44b67e3e1719b9220bde4b5bca44536b&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fmobile%2F2019-03-21%2F5c934568b99db.jpg";
//            }
            if (!TextUtils.isEmpty(image_url)) {
                Glide.with(context)
                        .asBitmap()
                        .load(image_url)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                if (resource != null) {
                                    showAdvDialog(context, advModel, resource);
                                } else {
                                    showAdvDialog(context, advModel, bitmap);
                                }
                            }
                        });
            } else {
                showAdvDialog(context, advModel, bitmap);
            }
        } else {
            showAdvDialog(context, advModel, bitmap);
        }
    }

    private static void showAdvDialog(Context context, AdvModel advModel, Bitmap bitmap) {
        AdvDialog advDialog = new AdvDialog(context, advModel, bitmap);
        advDialog.show();
    }


    private AdvDialog(Context context, AdvModel model, Bitmap bitmap) {
        super(context);
        this.model = model;
        this.resource = bitmap;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_mainmsg;
    }

    @Override
    protected void initView() {
        int width = resource.getWidth();
        int height = resource.getHeight();
        int maxWidth = (int) (DisplayUtils.getScreenWidthAndHight(getContext())[0] * 0.8f);
        int ivWidth = width;
        if (width >= maxWidth) {
            ivWidth = maxWidth;
        }
        int ivHeigh = (int) (((height * 1.0f) / (width * 1.0f)) * (ivWidth * 1.0f));
        Timber.d("--->>>>>>>>---width:" + width);
        Timber.d("--->>>>>>>>---height:" + height);
        Timber.d("--->>>>>>>>---ivWidth:" + ivWidth);
        Timber.d("--->>>>>>>>---ivHeigh:" + ivHeigh);
        FrameLayout.LayoutParams layoutParamsImg = (FrameLayout.LayoutParams) iv_mainmsg_img.getLayoutParams();
        layoutParamsImg.width = ivWidth;
        layoutParamsImg.height = ivHeigh;
        iv_mainmsg_img.setLayoutParams(layoutParamsImg);
        iv_mainmsg_img.setImageBitmap(resource);

        onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                iv_mainmsg_delete.setVisibility(View.VISIBLE);
                int rightImg = iv_mainmsg_img.getRight();
                int topImg = iv_mainmsg_img.getTop();
                int diff = DisplayUtils.dip2px(getContext(), 15);
                int left = rightImg - diff;
                int top = topImg - diff;
                int right = rightImg + diff;
                int bottom = top + diff;
                FrameLayout.LayoutParams layoutParamsDelete = (FrameLayout.LayoutParams) iv_mainmsg_delete.getLayoutParams();
                layoutParamsDelete.setMargins(left, top,
                        right, bottom);
                iv_mainmsg_delete.setLayoutParams(layoutParamsDelete);
            }
        };
        iv_mainmsg_img.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
    }

    @Override
    protected void initListener() {

    }

    @OnClick({R.id.view_mainmsg_bg, R.id.iv_mainmsg_img, R.id.iv_mainmsg_delete})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_mainmsg_delete:
            case R.id.view_mainmsg_bg:
                dismiss();
                break;
            case R.id.iv_mainmsg_img:
                CategoryActivity.startCategoryActivity(getContext(), model.getAction_url(), getString(R.string.h5_category_title));
                dismiss();
                break;
        }
    }

    @Override
    protected int getGravity() {
        return Gravity.CENTER;
    }

    @Override
    public void dismiss() {
        if (onGlobalLayoutListener != null) {
            iv_mainmsg_img.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
        }
        super.dismiss();
    }

}
